package com.jiubanqingchen.wish.kit;

import cn.hutool.core.util.ArrayUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;

import java.util.List;

/**
 * model支持类
 *
 * @author light_dust
 * @since 2021/1/2 20:54
 */
public class ModelKit {
    private static final ModelKit me = new ModelKit();

    public static ModelKit me() {
        return me;
    }

    /**
     * 显示model中的指定字段
     * @param model model对象
     * @param columns 显示列 ,分割
     */
    public void showColumnsForModel(Model<?> model, String columns) {
        if (model == null || StrKit.isBlank(columns)) return;
        String[] showColumnArr = columns.split(",");
        String[] columnArr = model._getAttrNames();
        for (String column : columnArr) {
            if (!ArrayUtil.contains(showColumnArr, column)) {
                model.remove(column);
            }
        }
    }

    /**
     * 显示model集合中的指定字段
     * @param modelList model集合
     * @param columns 显示列 ,分割
     */
    public void showColumnsForModelList(List<Model<?>> modelList, String columns) {
        if (BlankKit.isBlankList(modelList) || StrKit.isBlank(columns)) return;
        modelList.forEach(model -> showColumnsForModel(model, columns));
    }

    /**
     * 隐藏model中的指定字段
     * @param model model对象
     * @param columns 隐藏列 ,分割
     */
    public void hideColumnsForModel(Model<?> model, String columns) {
        if (model == null || StrKit.isBlank(columns)) return;
        String[] hideColumnArr = columns.split(",");
        String[] columnArr = model._getAttrNames();
        for (String column : columnArr) {
            if (ArrayUtil.contains(hideColumnArr, column)) {
                model.remove(column);
            }
        }
    }

    /**
     * 隐藏model集合中的指定字段
     * @param modelList model集合
     * @param columns 隐藏列 ,分割
     */
    public void hideColumnsForModelList(List<Model<?>> modelList, String columns) {
        if (BlankKit.isBlankList(modelList) || StrKit.isBlank(columns)) return;
        modelList.forEach(model -> hideColumnsForModel(model, columns));
    }
}
